<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'unitmanage:unitRegion:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
    destroyOnClose={true}
    @close="handleDrawerClose"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <template #footer>
        <Button  @click="closeDrawer">  <Icon icon="i-ant-design:close-outlined" />取消</Button>
        <Button v-if="record.isNewRecord!=false"  @click="addRegion">新增区域</Button>
        <Button type="primary" @click="handleSubmit"> <Icon icon="i-ant-design:check-outlined" />确认</Button>
    </template>
    <BasicForm @register="registerForm" ref="formRef" :key="formTimeKey" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsUnitmanageUnitRegionForm">
  import { ref, unref, computed, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { UnitRegion, unitRegionSave, unitRegionForm, unitRegionListData } from '/@/api/unitmanage/unitRegion';
  import { Office, officeTreeData, officeListData, officeTreeDataList } from '/@/api/sys/office';
  import { unitEnterpriseDominantListData } from "/@/api/unitmanage/unitEnterpriseDominant";
  import { unitBuildingListData } from "/@/api/unitmanage/unitBuilding";
  import { Button } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('unitmanage.unitRegion');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<UnitRegion>({} as UnitRegion);
  const id = ref(Number); 
  const peripheryData = ref([]);
  const enterpriseName = ref('');
  const enterpriseId = ref('');
  const unitCode = ref('');
  const isLoadingBuildings = ref(false); 
  const isLoadingPeriphery = ref(false); 

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.tid ? t('新增') : t('编辑'),
  }));

  const PeripheryUnitCode = ref('');
  const UnitCode=ref('');
  const buildingName = ref('');
  const ResUnitCode = ref('');
  const EnterpriseParams = ref<Recordable>({
    name:''
  });

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('区域名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('所属主体'),
      field: 'unitCode',
      fieldLabel: 'enterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
          onChange: (unitCode,enterpriseName)=>{
            UnitCode.value=unitCode
            // enterpriseName.value=enterpriseName
            record.value.enterpriseName=enterpriseName
            PeripheryUnitCode.value=unitCode
            console.log('选择的单位:', UnitCode.value);
          }
        };
      },
    },
    {
      label: t('所属建筑'),
      field: 'buildId',
      fieldLabel: 'buildName',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api: unitBuildingListData,
        params: computed(() => {
          return {
            unitCode: UnitCode.value? UnitCode.value : ResUnitCode.value
          };
        }),
        resultField: 'list',
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        onSearch:(value) => {
          buildingName.value = value;
          // console.log('输入的值:', value);
        },
        loading: isLoadingBuildings.value, 
      },
    },
    {
      label: t('楼层数'),
      field: 'floorNum',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('区域面积'),
      field: 'area',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('详细地址'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('联动区域'),
      field: 'periphery',
      fieldLabel: 'master',
      component: 'TreeSelect',
      componentProps: {
        api: unitRegionListData,
        key:"formTimeKey",
        params: computed(() => {
          return {
            unitCode: PeripheryUnitCode.value?UnitCode.value : ResUnitCode.value, 
          };
        }),
        resultField: 'list',
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        allowClear: true,
        treeCheckable: true,
        loading: isLoadingPeriphery.value, 
      },
    },
    {
      label: t('设备数量'),
      field: 'equNumber',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    // {
    //   label: t('区域负责人'),
    //   field: 'master',
    //   component: 'Input',
    //   componentProps: {
    //   }
    // },
    {
      label: t('区域联动人员'),
      field: 'regionLeader',
      component: 'Input',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await unitRegionForm(data);
    console.log(res);
    ResUnitCode.value = res.unitRegion.enterpriseId
    record.value = (res.unitRegion || {}) as UnitRegion;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

const formRef = ref<any>();
const formTimeKey=ref(Date.now());
const handleDrawerClose = () => {
  formRef.value.resetFields();
  PeripheryUnitCode.value = '';
  UnitCode.value = '';
  ResUnitCode.value = '';
}


  // 监听 PeripheryUnitCode 的变化
  watch(PeripheryUnitCode, async (newValue) => {
    if (newValue) {
      try {
        const res = await unitEnterpriseDominantListData({ unitCode: newValue });
        if (res.unionEnterprise) {
          PeripheryUnitCode.value = res.unionEnterprise; // 更新 PeripheryUnitCode 的值为 unionEnterprise
        }
      } catch (error) {
        console.error('获取联动企业数据失败', error);
      }
    }
  });

  async function handleSubmit() {
    try {
      let data = await validate();
      setDrawerProps({ confirmLoading: false });
      const officeData = await officeTreeData();
      data = {
        ...data,
        enterpriseName: record.value.enterpriseName? record.value.enterpriseName:EnterpriseParams.value.name,
        enterpriseId: record.value.unitCode,
        unitCode: record.value.unitCode? record.value.unitCode:UnitCode.value ,
      };

      console.log('data', data);
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };

      const res = await unitRegionSave(params, data);

      console.log(params);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

    // 新增 addRegion 方法
    const addRegion = async () => {
    console.log('新增建筑');
    await handleSubmit();
    await resetFields();
  };
</script>